import { _decorator, Component, Node, Label, tween, view, UITransform, Vec3, SpriteAtlas, SpriteFrame, Sprite, UIOpacity, EventTouch, find } from 'cc';
import { App } from '../App';
import { LoadMg } from '../tools/LoadMg';
import UtilTool from '../tools/UtilTool';
import { Prefab } from 'cc';
import { instantiate } from 'cc';
import { Layout } from 'cc';
import { ScrollView } from 'cc';
const { ccclass, property } = _decorator;

const MAX_HIGH = 1436 // 最大高度 (7个item)

/**
 * 选择列表
 * 超过一定个数时，进行滑动选择
 */
@ccclass('SelectListPanel')
export class SelectListPanel extends Component {
    @property(Node)
    node_parent: Node = null;

    @property(Node)
    contentNode : Node = null;

    @property(Prefab)
    itemPrefab: Prefab = null;

    @property(ScrollView)
    scNode : ScrollView = null;

    @property(Layout)
    layout : Layout = null;

    cb : Function = null;

    onLoad() {
        UtilTool.setScreen(this.node)
        this.node_parent.getComponent(UITransform).setContentSize(view.getVisibleSize())

        UtilTool.nodeActive(this.node_parent, 1, 0.16)
    }

    start() {
    }

    initData(textList, cb) {
        this.cb = cb
        for (let index = 0; index < textList.length; index++) {
            const text = textList[index];
            let item = instantiate(this.itemPrefab)
            item.parent = this.contentNode
            item.on(Node.EventType.TOUCH_END,(event: EventTouch) =>{
                this.clickItem(index)
            })
            let label = find("label",item).getComponent(Label)
            label.string = text
        }

        // 设置高度
        let itemSize = this.contentNode.children[0].getComponent(UITransform).height
        let high = this.layout.spacingY * (textList.length - 1) + itemSize * textList.length + this.layout.paddingTop*2
        let size = this.scNode.getComponent(UITransform)
        high = high > MAX_HIGH ? MAX_HIGH : high
        size.setContentSize(size.width, high)

        // content的位置为high
        this.contentNode.setPosition(0, high)

        this.scNode.scrollToTop(0.1)
        
    }

    /** 
     * 关闭
      */
    clickClose() {
        App.Audio.playOneShot("click")
        this.node.destroy();
    }

    clickItem(index) {
        App.Audio.playOneShot("click")
        this.cb(index)
        this.node.destroy();
    }
}

